package com.ljfiction.book.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.liulishuo.magicprogresswidget.MagicProgressBar;
import com.ljfiction.book.Baner.MyBookBean;
import com.ljfiction.book.Baner.MyDanmuBean;
import com.ljfiction.book.Baner.MyshupingBean;
import com.ljfiction.book.Baner.OtherUserBean;
import com.ljfiction.book.Baner.ShouCangBookBean;
import com.ljfiction.book.Dialog.IsOrNoDialog;
import com.ljfiction.book.MyView.CircularImageView;
import com.ljfiction.book.MyView.NoScrollListView;
import com.ljfiction.book.MyView.ObservableScrollView;
import com.ljfiction.book.R;
import com.ljfiction.book.adapter.UserCenterBooKAdapter;
import com.ljfiction.book.adapter.UserCenterShoucangBookAdapter;
import com.ljfiction.book.adapter.UserDuanpingAdapter;
import com.ljfiction.book.adapter.UserShupingAdapter;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.http.UserManageBean;
import com.ljfiction.book.tools.SettingManager;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class UserCenterActivity extends BaseActivity {


    @BindView(R.id.usercenter_email)
    ImageView usercenterEmail;
    @BindView(R.id.userImage_usercenter)
    CircularImageView userImageUsercenter;
    @BindView(R.id.useradd_usercenter)
    ImageView useraddUsercenter;
    @BindView(R.id.username2)
    TextView username2;
    @BindView(R.id.sex_usercenter)
    ImageView sexUsercenter;
    @BindView(R.id.progressbar_user)
    MagicProgressBar progressBar2;
    @BindView(R.id.guanzhu_usercenter)
    TextView guanzhuUsercenter;
    @BindView(R.id.fenshi_usercenter)
    TextView fenshiUsercenter;
    @BindView(R.id.allbook)
    TextView allbook;
    @BindView(R.id.review_usercent)
    TextView reviewUsercent;
    @BindView(R.id.recomenlistview_usercent)
    NoScrollListView recomenlistviewUsercent;
    @BindView(R.id.allbookrecoument_usercent)
    TextView allbookrecoumentUsercent;
    @BindView(R.id.reviewduan_usercent)
    TextView reviewduanUsercent;
    @BindView(R.id.recomenlistviewduan_usercent)
    NoScrollListView recomenlistviewduanUsercent;

    @BindView(R.id.back_usercenter)
    ImageView backUsercenter;
    @BindView(R.id.qianmingusercenter)
    TextView qianmingusercenter;
    @BindView(R.id.dengji)
    TextView dengji;
    @BindView(R.id.scrollview_usercenter)
    ObservableScrollView scrollviewUsercenter;
    @BindView(R.id.bookrecycle)
    RecyclerView bookrecycle;
    @BindView(R.id.tadeshujia)
    TextView tadeshujia;
    @BindView(R.id.nopinglun)
    TextView nopinglun;
    @BindView(R.id.noduanping)
    TextView noduanping;
    @BindView(R.id.allduanping)
    TextView allduanping;
    @BindView(R.id.toptext_boodatas)
    TextView toptextBoodatas;
    @BindView(R.id.usercentertop)
    RelativeLayout usercentertop;
    private int imageHeight;
    private String userId;
    private OtherUserBean otherUserBean;
    private OtherUserBean.DataBean usermessage;
    private List<MyBookBean.DataBean> booklist = new ArrayList<>();
    private int page = 1;
    private UserCenterBooKAdapter adapter;
    private Intent intent;
    private MyBookBean bookbean;
    private MyshupingBean myshupingBean;
    private UserShupingAdapter shupingAdapter;
    private MyDanmuBean myDanmuBean;
    private UserDuanpingAdapter duanpingAdapter;
    private List<MyDanmuBean.DataBean.ListBean> danmulist = new ArrayList<>();
    private List<MyshupingBean.DataBean.ListBean> shupinglist = new ArrayList<>();
    private IsOrNoDialog isOrNoDialog;
    private IsOrNoDialog isOrNoDialogok;
    private ShouCangBookBean shouCangBookBean;
    private List<ShouCangBookBean.DataBean.ListBean> shoucangbooklist = new ArrayList<>();
    private UserCenterShoucangBookAdapter shoucangadpter;
    private Intent intent1, intent3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_center);
        ButterKnife.bind(this);
        usercentertop.getBackground().setAlpha(255);
        userId = getIntent().getStringExtra("userId");

        intent1 = new Intent(this, ToEmailActivity.class);

        toShujiaView();
        intData();
        intUsermessage();
        //关注num
        toGuanzhunum("1");
        //粉丝num
        toGuanzhunum("0");
        //设置顶部
    }

    private void toShujiaView() {
        //设置布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        bookrecycle.setLayoutManager(linearLayoutManager);
        adapter = new UserCenterBooKAdapter(R.layout.userbook_item, booklist);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
              Intent  intent = new Intent(UserCenterActivity.this, BookDetailsActivity.class);
                intent.putExtra("bookId", String.valueOf(booklist.get(position).getBookId()));
                startActivity(intent);
            }
        });
        shoucangadpter = new UserCenterShoucangBookAdapter(R.layout.userbook_item, shoucangbooklist);
        shoucangadpter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent  intent = new Intent(UserCenterActivity.this, BookDetailsActivity.class);
                intent.putExtra("bookId", String.valueOf(shoucangbooklist.get(position).getBookId()));
                startActivity(intent);
            }
        });

    }

    private void toShupingView() {
        shupingAdapter = new UserShupingAdapter(shupinglist, this);
        recomenlistviewUsercent.setAdapter(shupingAdapter);
        recomenlistviewUsercent.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                intent3 = new Intent(UserCenterActivity.this, ShupingDatasActivity.class);
                intent3.putExtra("thisshuping", shupinglist.get(position));
                startActivityForResult(intent3, 8);
            }
        });

    }

    private void toDuanpingView() {
        duanpingAdapter = new UserDuanpingAdapter(danmulist, this);
        recomenlistviewduanUsercent.setAdapter(duanpingAdapter);


    }

    private void intUser() {
        //用户信息
        OkHttpUtils.post(HttpManager.IP + "/person-SimplifyUserInfo")

                .params("puserid", userId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        try {
                            otherUserBean = gson.fromJson(s, OtherUserBean.class);
                            if (otherUserBean.getReturnCode() == 200) {
                                usermessage = otherUserBean.getData();
                                toUserMassage();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void intUsermessage() {
        //用户信息
        OkHttpUtils.post(HttpManager.IP + "/person-SimplifyUserInfo")

                .params("puserid", userId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        try {
                            otherUserBean = gson.fromJson(s, OtherUserBean.class);
                            if (otherUserBean.getReturnCode() == 200) {
                                usermessage = otherUserBean.getData();
                                if (usermessage.getIsAuthor() == 1) {
                                    bookrecycle.setAdapter(adapter);
                                    toAutherBook();
                                } else {
                                    bookrecycle.setAdapter(shoucangadpter);
                                    toTabook();
                                }
                                toUserMassage();
                            } else {
                                showToast(otherUserBean.getMsg());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void intData() {
        //Ta的书评
        OkHttpUtils.post(HttpManager.IP + "/comm-commInfoByUserId")
                .params("userid", userId)
                .params("startPage", "1")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        try {
                            myshupingBean = gson.fromJson(s, MyshupingBean.class);
                            if (myshupingBean.getReturnCode() == 200) {
                                shupinglist.addAll(myshupingBean.getData().getList());
                                if (shupinglist.size() > 0) {
                                    nopinglun.setVisibility(View.GONE);
                                    toShupingView();
                                    allbookrecoumentUsercent.setText("全部" + myshupingBean.getData().getTotal() + "条");
                                } else {
                                    allbookrecoumentUsercent.setVisibility(View.GONE);
                                    recomenlistviewUsercent.setVisibility(View.GONE);
                                }
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }


                    }
                });
        //Ta的弹幕
        OkHttpUtils.get(HttpManager.IP + "/pcomm-getParagraphcommentuid/" + userId + "/1")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        try {
                            myDanmuBean = gson.fromJson(s, MyDanmuBean.class);
                            if (myDanmuBean.getReturnCode() == 200) {
                                danmulist.addAll(myDanmuBean.getData().getList());
                                if (danmulist.size() > 0) {
                                    noduanping.setVisibility(View.GONE);
                                    toDuanpingView();
                                    allduanping.setText("全部" + myDanmuBean.getData().getTotal()+ "条");
                                } else {
                                    allduanping.setVisibility(View.GONE);
                                    recomenlistviewduanUsercent.setVisibility(View.GONE);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }


                    }
                });

    }

    private void toTabook() {
        tadeshujia.setText("Ta的书架");
        //Ta的书架
        OkHttpUtils.post(HttpManager.IP + "/bookshelf-getuserbookshelf")

                .params("userid", userId)
                .params("startpage", String.valueOf(page))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            Gson gson = new Gson();
                            shouCangBookBean = gson.fromJson(s, ShouCangBookBean.class);
                            if (shouCangBookBean.getReturnCode() == 200) {
                                shoucangbooklist.addAll(shouCangBookBean.getData().getList());
                                if (shoucangbooklist.size() > 0) {

                                    allbook.setVisibility(View.GONE);
                                } else {
                                    allbook.setVisibility(View.VISIBLE);
                                    allbook.setText("Ta还没有书架");
                                }
                            }
                            shoucangadpter.notifyDataSetChanged();
                        } catch (JsonSyntaxException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void toAutherBook() {

        tadeshujia.setText("Ta的作品");
        OkHttpUtils.post(HttpManager.IP + "/book-AuthorAllBookInfo")
                .headers("token", "0")
                .params("authorId", String.valueOf(usermessage.getUserId()))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            Gson gson = new Gson();
                            bookbean = gson.fromJson(s, MyBookBean.class);
                            if (bookbean.getReturnCode()==200){
                                booklist.addAll(bookbean.getData());
                                if (booklist.size() > 0) {
                                    allbook.setVisibility(View.GONE);
                                    adapter.notifyDataSetChanged();
                                } else {
                                    allbook.setVisibility(View.VISIBLE);
                                    allbook.setText("Ta还没开新书");
                                }
                            }else {
                                allbook.setVisibility(View.VISIBLE);
                                allbook.setText("Ta还没开新书");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void toUserMassage() {
        Glide.with(this).load(usermessage.getUserHeadPortraitURL()).into(userImageUsercenter);
        username2.setText(usermessage.getPseudonym());
        qianmingusercenter.setText(usermessage.getUserAutograph());
        if (usermessage.getUserSex() == 0) {
            sexUsercenter.setImageResource(R.mipmap.sex_n);
        } else {
            sexUsercenter.setImageResource(R.mipmap.sex_v);
        }
        dengji.setText("LV"+String.valueOf(usermessage.getUserGrade()));
        progressBar2.setPercent((float)(usermessage.getIntegration()-usermessage.getTopSource())/(usermessage.getDownSource()-usermessage.getTopSource()));
        if (UserManageBean.isLogin() && UserManageBean.userBean.getUserId() == usermessage.getUserId()) {
            useraddUsercenter.setVisibility(View.GONE);
            usercenterEmail.setVisibility(View.GONE);
            return;
        }
        useraddUsercenter.setVisibility(View.VISIBLE);
        usercenterEmail.setVisibility(View.VISIBLE);
        if (usermessage.getIsfollow() == 1 && UserManageBean.isLogin()) {
            useraddUsercenter.setImageResource(R.mipmap.guanzhule);
        } else {
            useraddUsercenter.setImageResource(R.mipmap.guanzhu);
        }

    }

    private void toGuanzhunum(final String type) {
        OkHttpUtils.get(HttpManager.IP + "/fans-followCount/" + userId + "/" + type)

                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        switch (type) {
                            case "1":
                                try {
                                    JSONObject jso = new JSONObject(s);
                                    if (jso.getInt("returnCode") == 200) {
                                        fenshiUsercenter.setText("粉丝 " + String.valueOf(jso.getInt("data")));
                                    } else {
                                        fenshiUsercenter.setText("粉丝");
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                break;
                            case "0":
                                try {
                                    JSONObject js = new JSONObject(s);
                                    if (js.getInt("returnCode") == 200) {
                                        guanzhuUsercenter.setText("关注 " + String.valueOf(js.getInt("data")));
                                    } else {
                                        guanzhuUsercenter.setText("关注");
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                break;
                        }
                    }
                });
    }

    @OnClick({R.id.back_usercenter, R.id.usercenter_email, R.id.useradd_usercenter, R.id.guanzhu_usercenter, R.id.fenshi_usercenter, R.id.allbookrecoument_usercent, R.id.allduanping})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_usercenter:
                goBack();
                break;
            case R.id.usercenter_email:
                if (!UserManageBean.isLogin(this)) {
                    return;
                }
                intent1.putExtra("userName", username2.getText().toString());
                intent1.putExtra("userId", userId);
                intent1.putExtra("userImageUrl", usermessage.getUserHeadPortraitURL());
                startActivity(intent1);
                break;
            case R.id.useradd_usercenter:
                if (!UserManageBean.isLogin(this)) {
                    return;
                }
                if (userId.equals(String.valueOf(UserManageBean.userBean.getUserId()))){
                    showToast("不能关注自己哦");
                    return;
                }
                if (usermessage.getIsfollow() == 0) {
                    isOrNoDialogok = new IsOrNoDialog(this, "确定关注此人？", true);
                    isOrNoDialogok.setListener(new IsOrNoDialog.Listener() {
                        @Override
                        public void okClick() {
                            toAddGuanzhu();
                        }

                        @Override
                        public void closeClick() {

                        }
                    });
                } else {
                    isOrNoDialog = new IsOrNoDialog(this, "确定取消关注？", true);
                    isOrNoDialog.setListener(new IsOrNoDialog.Listener() {
                        @Override
                        public void okClick() {
                            deletguanzhu();

                        }

                        @Override
                        public void closeClick() {

                        }
                    });
                }

                break;
            case R.id.guanzhu_usercenter:
                if (userId.equals(String.valueOf(UserManageBean.userBean.getUserId()))){
                    intent=new Intent(UserCenterActivity.this, MyfensiActivity.class);
                    intent.putExtra("type",1);
                }else {
                    intent=new Intent(UserCenterActivity.this, OtherfensiActivity.class);
                    intent.putExtra("type",1);
                    intent.putExtra("userId",userId);
                }

                startActivity(intent);
                break;
            case R.id.fenshi_usercenter:
                if (userId.equals(String.valueOf(UserManageBean.userBean.getUserId()))){
                    intent=new Intent(UserCenterActivity.this, MyfensiActivity.class);
                    intent.putExtra("type",0);
                }else {
                    intent=new Intent(UserCenterActivity.this, OtherfensiActivity.class);
                    intent.putExtra("type",0);
                    intent.putExtra("userId",userId);
                }
                startActivity(intent);
                break;
            case R.id.allbookrecoument_usercent:
                intent = new Intent(this, MyshupingActivity.class);
                intent.putExtra("type", 1);
                intent.putExtra("userId",userId);
                startActivity(intent);
                break;
            case R.id.allduanping:
                intent = new Intent(this, MyshupingActivity.class);
                intent.putExtra("type", 2);
                intent.putExtra("userId",userId);
                startActivity(intent);
                break;
        }
    }

    private void deletguanzhu() {
        OkHttpUtils.post(HttpManager.IP + "/fans-CancelFollow/")

                .params("followId", userId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            JSONObject jso = new JSONObject(s);
                            if (jso.getInt("returnCode") == 200) {
                                usermessage.setIsfollow(0);
                                useraddUsercenter.setImageResource(R.mipmap.guanzhu);
                                toGuanzhunum("1");
                            }else if (jso.getInt("returnCode") == 400){
                                Intent intent=new Intent(UserCenterActivity.this, LoginActivity.class);
                                startActivity(intent);
                            }
                            showToast(jso.getString("msg"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        usercentertop.getBackground().setAlpha(255);
        intUser();
    }

    private void toAddGuanzhu() {

        OkHttpUtils.post(HttpManager.IP + "/fans-addFans")

                .params("followId", userId)
                .params("followUserName", usermessage.getPseudonym())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            JSONObject js = new JSONObject(s);
                            if (js.getInt("returnCode") == 200) {
                                usermessage.setIsfollow(1);
                                useraddUsercenter.setImageResource(R.mipmap.guanzhule);
                                toGuanzhunum("1");

                            }else if (400 == js.getInt("returnCode") ) {
                                Intent intent=new Intent(UserCenterActivity.this,LoginActivity.class);
                                startActivity(intent);
                            }
                            showToast(js.getString("msg"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }


}
